package com.yjzx.care;

import com.yjzx.care.base.BaseLoop;
import com.yjzx.care.base.Constant;
import com.yjzx.care.base.LoopBuilder;

import java.util.function.BooleanSupplier;
import java.util.function.Consumer;

/**
 * @author yjzx
 * @date 2023/12/28
 * @description while 循环
 */
public class LoopWhile extends BaseLoop {
    public static class LoopWhileBuilder implements LoopBuilder {
        protected BooleanSupplier judge;
        protected Consumer<LoopWhile> loopBody;

        protected LoopWhileBuilder() {
        }

        /**
         * 必要属性填充
         *
         * @param judge    条件判断输入
         * @param loopBody 循环体
         * @return 本身
         */
        public LoopWhileBuilder set(BooleanSupplier judge, Consumer<LoopWhile> loopBody) {
            this.judge = judge;
            this.loopBody = loopBody;
            return this;
        }

        public LoopWhile setAndBuild(BooleanSupplier judge, Consumer<LoopWhile> loopBody) {
            this.judge = judge;
            this.loopBody = loopBody;
            return build();
        }
        /**
         * 条件判断输入
         * @param judge 条件判断
         * @return
         */
        public LoopWhileBuilder withJudge(BooleanSupplier judge) {
            this.judge = judge;
            return this;
        }

        /**
         * 循环体
         * @param loopBody 循环体
         * @return
         */
        public LoopWhileBuilder withLoopBody(Consumer<LoopWhile> loopBody) {
            this.loopBody = loopBody;
            return this;
        }

        @Override
        public LoopWhile build() {
            if (this.judge==null) {
                this.judge = Constant.JUDGE_TO_TRUE;
            }
            if (this.loopBody==null) {
                return new LoopWhile(judge,Constant.loopBody());
            }
            return new LoopWhile(judge,loopBody);
        }
    }

    LoopWhile(BooleanSupplier judge, Consumer<LoopWhile> loopBody) {
        this.loopBody0(judge, loopBody);
    }

    LoopWhile() {
    }


    /**
     * 循环执行
     *
     * @param judge    判断条件
     * @param loopBody 循环体
     */
    public LoopWhile loopBody(BooleanSupplier judge, Consumer<LoopWhile> loopBody) {
        loopBody0(judge, loopBody);
        return this;
    }

    private void loopBody0(BooleanSupplier judge, Consumer<LoopWhile> loopBody) {
        this.isLoop();
        while (this.isBreak() && judge.getAsBoolean()) {
            loopBody.accept(this);
        }
        this.toBreak();
    }
}
